<?php
namespace App\Services;
use EasyWeChat\Pay\Application;
use Exception;
class WeChatPayService
{
    protected $config;
    public function __construct()
    {
        $this->config = [
            'mch_id' => config('wechat.payment.mch_id'),
            'private_key' => file_get_contents(config('wechat.payment.key_path')),
            'certificate' => file_get_contents(config('wechat.payment.cert_path')),
            'secret_key' => config('wechat.payment.api_key'),
            'http' => ['timeout' => 5.0]
        ];
    }

    public function createH5Order(string $orderNo, float $amount, string $description)
    {
        $app = new Application($this->config);
        $response = $app->getClient()->postJson('/v3/pay/transactions/h5', [
            'mchid' => $this->config['mch_id'],
            'out_trade_no' => $orderNo,
            'description' => $description,
            'notify_url' => config('wechat.payment.notify_url'),
            'amount' => [
                'total' => intval($amount * 100),
                'currency' => 'CNY'
            ],
            'scene_info' => [
                'payer_client_ip' => request()->ip(),
                'h5_info' => [
                    'type' => 'Wap',
                    'app_name' => config('app.name'),
                    'app_url' => config('app.url')
                ]
            ]
        ]);

        if ($response->isSuccess()) {
            return $response->toArray();
        }
        throw new Exception('支付创建失败: '.$response->getContent());
    }
    public function initConfig(){
        return new Application($this->config);
    }
}



